package com.yksj.healthtalk.ui.chatting;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;

import com.yksj.healthtalk.adapter.ChatLatelyListAdapter;
import com.yksj.healthtalk.adapter.ChatLatelyListAdapter.ViewHolder;
import com.yksj.healthtalk.adapter.ChatLatelyListAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.ChatLatelyListAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.BaseInfoEntity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.FragmentContentActivity;
import com.yksj.healthtalk.ui.MainTabUI;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.EntityObjUtils;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 我的消息
 * @author jack_tang
 */
public class ChatLatelyListActivity extends BaseFragmentActivity implements OnClickListener,
	OnChildClickListener,OnBuyTicketHandlerListener, onClickSalonAttentionListener, onClickFriendAttentionListener{
	
	//返回到主界面
	boolean mIsBackToMainUI = false;
	ExpandableListView mExpandableListView;
	ChatLatelyListAdapter mAdapter;
	ConcurrentHashMap<String,Object> mInfoHashMap;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	class HttpResponseHandler extends ObjectHttpResponseHandler{
		final BaseInfoEntity mInfoEntity;
		public HttpResponseHandler(BaseInfoEntity entity) {
			this.mInfoEntity = entity;
		}
		@Override
		public Object onParseResponse(String content) {
			try {
				JSONObject object = new JSONObject(content);
				if(mInfoEntity instanceof CustomerInfoEntity){
					CustomerInfoEntity  entity = DataParseUtil.jsonToCustmerInfo(object);
					EntityObjUtils.copyProperties(entity, mInfoEntity);
				}else{
					final GroupInfoEntity entity = DataParseUtil.jsonToGroupInfoEntity(object);
					EntityObjUtils.copyProperties(entity, mInfoEntity);
				}
				return mInfoEntity;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		public void onSuccess(Object response) {
			if(response != null){
				if(mInfoEntity.mViewHold != null){
					WeakReference reference = (WeakReference)mInfoEntity.mViewHold;
					if(!reference.isEnqueued())mAdapter.onBindData((ViewHolder)reference.get(),mInfoEntity);
				}
			}
		}
	}
	
	class DataUpdateTask extends AsyncTask<Void,Void,Object>{
		final List<String[]> groupList = new ArrayList<String[]>();
		final List<List<BaseInfoEntity>> childList = new ArrayList<List<BaseInfoEntity>>();
		@Override
		protected Object doInBackground(Void... params) {
			final AppData data = HTalkApplication.getAppData();
			final ConcurrentHashMap<String,List<MessageEntity>>  map = data.messageCllection;
			final ConcurrentHashMap<String,Object> infoHashMap = mInfoHashMap;
			final Set<String> keys = map.keySet();
			List<String> creatGroupList = data.getCreatedGroupIdList();
			List<String> interestGroupList = data.getInterestGroupIdList();
			List<String> interestFriendList = data.getInterestFriendIdList();
			List<String> docotorFriendList = data.getDoctorIdList();
			List<String> customerIdList = data.getCustomerIdList();
			
			Map<String,String[]> titleMap = new LinkedHashMap<String,String[]>();
				titleMap.put("助理消息", new String[]{"助理消息","0"});
				titleMap.put("医生消息", new String[]{"医生消息","0"});
				titleMap.put("患者消息", new String[]{"患者消息","0"});
				titleMap.put("朋友消息",new String[]{"朋友消息","0"});
				titleMap.put("话题消息", new String[]{"话题消息","0"});
				titleMap.put("陌生人消息", new String[]{"陌生人消息","0"});
			
			
			
			
			Map<String,List<BaseInfoEntity>> listMap = new LinkedHashMap<String,List<BaseInfoEntity>>();
			listMap.put("助理消息",new ArrayList<BaseInfoEntity>());
			listMap.put("医生消息",new ArrayList<BaseInfoEntity>());
			listMap.put("患者消息",new ArrayList<BaseInfoEntity>());
			listMap.put("朋友消息",new ArrayList<BaseInfoEntity>());
			listMap.put("话题消息",new ArrayList<BaseInfoEntity>());
			listMap.put("陌生人消息",new ArrayList<BaseInfoEntity>());
			
			
			for (String str : keys) {//多美医生
				if(SmartFoxClient.helperId.equals(str)){
					final int size = map.get(str).size();
					String strArray[] = new String[]{"助理消息",String.valueOf(size)};
					titleMap.put("助理消息",strArray);
					List<BaseInfoEntity> list = new ArrayList<BaseInfoEntity>();
					list.add((BaseInfoEntity)infoHashMap.get(str));
					listMap.put("助理消息",list);
				}else{//话题
					if(creatGroupList.contains(str) || interestGroupList.contains(str) || (map.get(str) != null && map.get(str).get(0).getGroupId() != null)){
						final int size = map.get(str).size();
						String[] strArray = null;
						List<BaseInfoEntity> list;
						if(listMap.containsKey("话题消息")){
							strArray = titleMap.get("话题消息");
							list = listMap.get("话题消息");
						}else{
							strArray = new String[]{"话题消息","0"};
							list = new ArrayList<BaseInfoEntity>();
							titleMap.put("话题消息",strArray);
							listMap.put("话题消息",list);
						}
						String sizeStr = strArray[1];
						sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
						strArray[1] = sizeStr;
						GroupInfoEntity entity = null;
						if(infoHashMap.containsKey(str)){
							entity = (GroupInfoEntity)infoHashMap.get(str);
						}else{
							entity = new GroupInfoEntity();
							entity.setId(str);
							infoHashMap.put(str,entity);
							Message msg = mHandler.obtainMessage();
							msg.what = 2;
							msg.obj = entity;
							mHandler.sendMessage(msg);
						}
						list.add(entity);
					}else if(docotorFriendList.contains(str)){//我的医生
						final int size = map.get(str).size();
						String[] strArray = null;
						List<BaseInfoEntity> list;
						if(listMap.containsKey("医生消息")){
							strArray = titleMap.get("医生消息");
							list = listMap.get("医生消息");
						}else{
							strArray = new String[]{"医生消息","0"};
							list = new ArrayList<BaseInfoEntity>();
							titleMap.put("医生消息",strArray);
							listMap.put("医生消息",list);
						}
						String sizeStr = strArray[1];
						sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
						strArray[1] = sizeStr;
						CustomerInfoEntity entity = null;
						if(infoHashMap.containsKey(str)){
							entity = (CustomerInfoEntity)infoHashMap.get(str);
						}else{
							entity = new CustomerInfoEntity();
							entity.setId(str);
							infoHashMap.put(str,entity);
							Message msg = mHandler.obtainMessage();
							msg.what = 2;
							msg.obj = entity;
							mHandler.sendMessage(msg);
						}
						list.add(entity);
					}else if(interestFriendList.contains(str)){//我的朋友
						final int size = map.get(str).size();
						String[] strArray = null;
						List<BaseInfoEntity> list;
						if(listMap.containsKey("朋友消息")){
							strArray = titleMap.get("朋友消息");
							list = listMap.get("朋友消息");
						}else{
							strArray = new String[]{"朋友消息","0"};
							list = new ArrayList<BaseInfoEntity>();
							titleMap.put("朋友消息",strArray);
							listMap.put("朋友消息",list);
						}
						String sizeStr = strArray[1];
						sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
						strArray[1] = sizeStr;
						CustomerInfoEntity entity = null;
						if(infoHashMap.containsKey(str)){
							entity = (CustomerInfoEntity)infoHashMap.get(str);
						}else{
							entity = new CustomerInfoEntity();
							entity.setId(str);
							infoHashMap.put(str,entity);
							Message msg = mHandler.obtainMessage();
							msg.what = 2;
							msg.obj = entity;
							mHandler.sendMessage(msg);
						}
						list.add(entity);
					}else if(customerIdList.contains(str)){//我的客户
						final int size = map.get(str).size();
						String[] strArray = null;
						List<BaseInfoEntity> list;
						if(listMap.containsKey("患者消息")){
							strArray = titleMap.get("患者消息");
							list = listMap.get("患者消息");
						}else{
							strArray = new String[]{"患者消息","0"};
							list = new ArrayList<BaseInfoEntity>();
							titleMap.put("患者消息",strArray);
							listMap.put("患者消息",list);
						}
						String sizeStr = strArray[1];
						sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
						strArray[1] = sizeStr;
						CustomerInfoEntity entity = null;
						if(infoHashMap.containsKey(str)){
							entity = (CustomerInfoEntity)infoHashMap.get(str);
						}else{
							entity = new CustomerInfoEntity();
							entity.setId(str);
							infoHashMap.put(str,entity);
							Message msg = mHandler.obtainMessage();
							msg.what = 2;
							msg.obj = entity;
							mHandler.sendMessage(msg);
						}
						list.add(entity);
					}else{//陌生人
						final int size = map.get(str).size();
						String[] strArray = null;
						List<BaseInfoEntity> list;
						if(listMap.containsKey("陌生人消息")){
							strArray = titleMap.get("陌生人消息");
							list = listMap.get("陌生人消息");
						}else{
							strArray = new String[]{"陌生人消息","0"};
							list = new ArrayList<BaseInfoEntity>();
							titleMap.put("陌生人消息",strArray);
							listMap.put("陌生人消息",list);
						}
						String sizeStr = strArray[1];
						sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
						strArray[1] = sizeStr;
						CustomerInfoEntity entity = null;
						if(infoHashMap.containsKey(str)){
							entity = (CustomerInfoEntity)infoHashMap.get(str);
						}else{
							entity = new CustomerInfoEntity();
							entity.setId(str);
							infoHashMap.put(str,entity);
							Message msg = mHandler.obtainMessage();
							msg.what = 2;
							msg.obj = entity;
							mHandler.sendMessage(msg);
						}
						list.add(entity);
					}
				}
			}
			
			final Map<String,List<String>> map2 = SharePreUtils.fatchChatLatelyList();
			if(!map2.isEmpty()) {
				//单聊
				final List<String> singList = map2.get("2");
				//群聊
				final List<String> groupList = map2.get("1");
				//群
				for (String str : groupList) {
					if(map.containsKey(str)) continue;
//					if(! (creatGroupList.contains(str)|| interestGroupList.contains(str) || (map.get(str) != null && map.get(str).get(0).getGroupId() != null)))continue;
					if(! (creatGroupList.contains(str)|| interestGroupList.contains(str)))continue;
					final int size = 0;
					String[] strArray = null;
					List<BaseInfoEntity> list;
					if(listMap.containsKey("话题消息")){
						strArray = titleMap.get("话题消息");
						list = listMap.get("话题消息");
					}else{
						strArray = new String[]{"话题消息","0"};
						list = new ArrayList<BaseInfoEntity>();
						titleMap.put("话题消息",strArray);
						listMap.put("话题消息",list);
					}
					String sizeStr = strArray[1];
					sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
					strArray[1] = sizeStr;
					GroupInfoEntity entity = null;
					if(infoHashMap.containsKey(str)){
						entity = (GroupInfoEntity)infoHashMap.get(str);
					}else{
						entity = new GroupInfoEntity();
						entity.setId(str);
						infoHashMap.put(str,entity);
						Message msg = mHandler.obtainMessage();
						msg.what = 2;
						msg.obj = entity;
						mHandler.sendMessage(msg);
					}
					list.add(entity);
				}
				
				//单聊
				for (String str : singList) {
					if(map.containsKey(str)) continue;
					if(SmartFoxClient.helperId.equals(str)){
						final int size = 0;
						String strArray[] = new String[]{"助理消息",String.valueOf(size)};
						titleMap.put("助理消息",strArray);
						List<BaseInfoEntity> list = new ArrayList<BaseInfoEntity>();
						list.add((BaseInfoEntity)infoHashMap.get(str));
						listMap.put("助理消息",list);
					}else{
						if(docotorFriendList.contains(str)){
							final int size = 0;
							String[] strArray = null;
							List<BaseInfoEntity> list;
							if(listMap.containsKey("医生消息")){
								strArray = titleMap.get("医生消息");
								list = listMap.get("医生消息");
							}else{
								strArray = new String[]{"医生消息","0"};
								list = new ArrayList<BaseInfoEntity>();
								titleMap.put("医生消息",strArray);
								listMap.put("医生消息",list);
							}
							String sizeStr = strArray[1];
							sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
							strArray[1] = sizeStr;
							CustomerInfoEntity entity = null;
							if(infoHashMap.containsKey(str)){
								entity = (CustomerInfoEntity)infoHashMap.get(str);
							}else{
								entity = new CustomerInfoEntity();
								entity.setId(str);
								infoHashMap.put(str,entity);
								Message msg = mHandler.obtainMessage();
								msg.what = 2;
								msg.obj = entity;
								mHandler.sendMessage(msg);
							}
							list.add(entity);
						}else if(interestFriendList.contains(str)){
							final int size = 0;
							String[] strArray = null;
							List<BaseInfoEntity> list;
							if(listMap.containsKey("朋友消息")){
								strArray = titleMap.get("朋友消息");
								list = listMap.get("朋友消息");
							}else{
								strArray = new String[]{"朋友消息","0"};
								list = new ArrayList<BaseInfoEntity>();
								titleMap.put("朋友消息",strArray);
								listMap.put("朋友消息",list);
							}
							String sizeStr = strArray[1];
							sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
							strArray[1] = sizeStr;
							CustomerInfoEntity entity = null;
							if(infoHashMap.containsKey(str)){
								entity = (CustomerInfoEntity)infoHashMap.get(str);
							}else{
								entity = new CustomerInfoEntity();
								entity.setId(str);
								infoHashMap.put(str,entity);
								Message msg = mHandler.obtainMessage();
								msg.what = 2;
								msg.obj = entity;
								mHandler.sendMessage(msg);
							}
							list.add(entity);
						}else if(customerIdList.contains(str)){
							final int size = 0;
							String[] strArray = null;
							List<BaseInfoEntity> list;
							if(listMap.containsKey("患者消息")){
								strArray = titleMap.get("患者消息");
								list = listMap.get("患者消息");
							}else{
								strArray = new String[]{"患者消息","0"};
								list = new ArrayList<BaseInfoEntity>();
								titleMap.put("患者消息",strArray);
								listMap.put("患者消息",list);
							}
							String sizeStr = strArray[1];
							sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
							strArray[1] = sizeStr;
							CustomerInfoEntity entity = null;
							if(infoHashMap.containsKey(str)){
								entity = (CustomerInfoEntity)infoHashMap.get(str);
							}else{
								entity = new CustomerInfoEntity();
								entity.setId(str);
								infoHashMap.put(str,entity);
								Message msg = mHandler.obtainMessage();
								msg.what = 2;
								msg.obj = entity;
								mHandler.sendMessage(msg);
							}
							list.add(entity);
						}else{
							final int size = 0;
							String[] strArray = null;
							List<BaseInfoEntity> list;
							if(listMap.containsKey("陌生人消息")){
								strArray = titleMap.get("陌生人消息");
								list = listMap.get("陌生人消息");
							}else{
								strArray = new String[]{"陌生人消息","0"};
								list = new ArrayList<BaseInfoEntity>();
								titleMap.put("陌生人消息",strArray);
								listMap.put("陌生人消息",list);
							}
							String sizeStr = strArray[1];
							sizeStr = String.valueOf(Integer.valueOf(sizeStr) + size);
							strArray[1] = sizeStr;
							CustomerInfoEntity entity = null;
							if(infoHashMap.containsKey(str)){
								entity = (CustomerInfoEntity)infoHashMap.get(str);
							}else{
								entity = new CustomerInfoEntity();
								entity.setId(str);
								infoHashMap.put(str,entity);
								Message msg = mHandler.obtainMessage();
								msg.what = 2;
								msg.obj = entity;
								mHandler.sendMessage(msg);
							}
							list.add(entity);
						}
					}
				}
			}
			
			groupList.addAll(titleMap.values());
			childList.addAll(listMap.values());
			return null;
		}
		@Override
		protected void onPostExecute(Object result) {
			mAdapter.onUpdateData(groupList,childList);
			onSaveList();
		}
	}
	
	final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			//更新列表
			if(!isFinishing()){
				if(msg.what == 1){
					new DataUpdateTask().execute();
				}else if(msg.what == 2){//查询资料
					Object object = msg.obj;
					if(object instanceof CustomerInfoEntity){
						HttpRestClient.doHttpFindCustomerInfoByCustId(null, null,((CustomerInfoEntity)object).getId(),null,new HttpResponseHandler((CustomerInfoEntity)object));
					}else if(object instanceof GroupInfoEntity){
						HttpRestClient.doHttpSalonToId(SmartFoxClient.getLoginUserId(),((GroupInfoEntity)object).getId(), new HttpResponseHandler((GroupInfoEntity)object));
					}
				}
			}
		};	
	};
	
	final BroadcastReceiver mReceiver = new BroadcastReceiver(){
		public void onReceive(android.content.Context context, android.content.Intent intent) {
			if(!isFinishing()){
				final String action = intent.getAction();
				if(MessagePushService.ACTION_MESSAGE.equals(action) || MessagePushService.ACTION_OFFLINE_MESSAGE.equals(action)){
					mHandler.sendEmptyMessage(1);
				}else if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
					LodingFragmentDialog.dismiss(getSupportFragmentManager());
					String result = intent.getStringExtra("result");
					if (result.equals("0")) {
						ToastUtil.showShort(ChatLatelyListActivity.this, R.string.groupNewFail);
					} else if (result.equals("-1")) {
						ToastUtil.showShort(ChatLatelyListActivity.this,R.string.against__blacklist_operations);
					} else {
						FriendHttpUtil.requestAttentionTofriendsResult(ChatLatelyListActivity.this, cacheCustomerInfoEntity, mAppData);
						mHandler.sendEmptyMessage(1);
					}
				}else if(action.equals(MessagePushService.ACTION_COLLECT_GROUP)){
					LodingFragmentDialog.dismiss(getSupportFragmentManager());
					String result = intent.getStringExtra("result");
					if (result.equals("0")) {
						ToastUtil.showShort(ChatLatelyListActivity.this, R.string.groupNewFail);
					} else {
						SalonHttpUtil.requestAttentionToSalonResult(ChatLatelyListActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
						mHandler.sendEmptyMessage(1);
					}
				}else if(action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)){
					LodingFragmentDialog.dismiss(getSupportFragmentManager());
					String result = intent.getStringExtra("result");
					if (result.equals("0")) {
						ToastUtil.showShort(ChatLatelyListActivity.this, R.string.groupNewFail);
					} else {
						SalonHttpUtil.requestUnfollowToSalonResult(ChatLatelyListActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
						deleteMessageFromUserID(cacheGroupInfoEntity.getId());
					}
				
				}
			}
		};
	};
	
	private AppData mAppData;
	private ChatUserHelper chatUserHelper;
	private GroupInfoEntity cacheGroupInfoEntity;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		HTalkApplication.getApplication().cancelNotify();
		chatUserHelper = ChatUserHelper.getInstance();
		setContentView(R.layout.chat_lately_layout);
		mIsBackToMainUI = getIntent().getBooleanExtra("notifi",false);
		initTitle();
		mAppData = HTalkApplication.getAppData();
		mInfoHashMap = new ConcurrentHashMap<String,Object>(HTalkApplication.getAppData().cacheInformation);
		titleLeftBtn.setOnClickListener(this);
		setTitle("我的消息");
		setRight("消息直播", this);
		
		mExpandableListView = (ExpandableListView)findViewById(android.R.id.list);
		mExpandableListView.setAdapter(mAdapter = new ChatLatelyListAdapter(getLayoutInflater(),this));
		mExpandableListView.setOnChildClickListener(this);
		mAdapter.setonClickFriendAttentionListener(this);
		mAdapter.setonClickSalonAttentionListener(this);
		
		
		registerForContextMenu(mExpandableListView);
		
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_OFFLINE_MESSAGE);
		registerReceiver(mReceiver,filter);
		mHandler.sendEmptyMessage(1);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(mReceiver);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo)menuInfo;
		long position = info.packedPosition;
		int type = ExpandableListView.getPackedPositionType(position);
		if(type == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
			menu.setHeaderTitle("操作");
			menu.add(1, 1,1,"删除");
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	
	/**
	 * 从缓存中加载消息
	 */
	private List<MessageEntity> onLoadMesgForCache(String key){
		final List<MessageEntity> list = HTalkApplication.getAppData().messageCllection.get(key);
		if(list != null)HTalkApplication.getAppData().messageCllection.remove(key);
		return list;
	}
	
	/**
	 * 删除消息
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final ExpandableListContextMenuInfo menuInfo = (ExpandableListContextMenuInfo) item.getMenuInfo();
		int type = ExpandableListView.getPackedPositionType(menuInfo.packedPosition);
		if(type == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
			final int childP = ExpandableListView.getPackedPositionChild(menuInfo.packedPosition);
			final int groupP = ExpandableListView.getPackedPositionGroup(menuInfo.packedPosition);
			final BaseInfoEntity entity = mAdapter.childList.get(groupP).get(childP);
			final ConcurrentHashMap<String,List<MessageEntity>> map = HTalkApplication.getAppData().messageCllection;
			//有消息需要删除消息
			if(map.containsKey(entity.getId())){
				List<MessageEntity> list = map.get(entity.getId());
				final JSONArray buffer=new JSONArray();
				for (MessageEntity messageEntity : list) {
					String id = messageEntity.getServerId();
					if(id == null)continue;
					buffer.put(id);
				}
				HttpRestClient.doHttpDeleteLeaveOnlineMessage(SmartFoxClient.getLoginUserId(),buffer.toString(),new AsyncHttpResponseHandler(this){
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(content);
							if(1==jsonObject.optInt("error_code",-1)){//删除成功
									onLoadMesgForCache(entity.getId());
								List<String> strings=new ArrayList<String>();
								for (int i = 0; i < buffer.length(); i++) {
									HTalkApplication.getAppData().messageMap.remove(buffer.get(i).toString());
									strings.add(buffer.get(i).toString());
								}
								ChatUserHelper.getInstance().updateChatMesageDeleteState(strings);
								mAdapter.childList.get(groupP).remove(childP);
								mAdapter.notifyDataSetChanged();
								onSaveList();
								mHandler.sendEmptyMessage(1);
							}else{
								ToastUtil.showToastPanl(jsonObject.optString("error_message","删除失败"));
							}
							
						} catch (JSONException e) {
						}
					}
					
				});
			}
		}
		return super.onContextItemSelected(item);
	}
	
	
	/**
	 * 保存消息到本地
	 */
	private void onSaveList(){
		final Map<String,List<String>> map = new HashMap<String, List<String>>();
		final List<String> singList  = new ArrayList<String>();
		final List<String> groupList  = new ArrayList<String>();
		map.put("1",groupList);//群
		map.put("2",singList);//个人
		//保存到本地
		final List<List<BaseInfoEntity>> list = mAdapter.childList;
		for (List<BaseInfoEntity> list2 : list) {
			for (BaseInfoEntity baseInfoEntity : list2) {
				if(baseInfoEntity instanceof GroupInfoEntity){
					groupList.add(baseInfoEntity.getId());
				}else{
					singList.add(baseInfoEntity.getId());
				}
			}
		}
		SharePreUtils.saveChatLatelyList(map);
	}
	

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			if(mIsBackToMainUI){
				Intent intent = new Intent(this,MainTabUI.class);
				intent.putExtra("notifi",true);
				startActivity(intent);
			}else{
				onBackPressed();
			}
			break;
		case R.id.title_right2://公共消息
			Intent intent = new Intent(this,FragmentContentActivity.class);
			intent.putExtra("type",1);
			startActivity(intent);
			break;
		}
	}
	

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		Object object = mAdapter.getChild(groupPosition, childPosition);
		if(object instanceof CustomerInfoEntity){
			final CustomerInfoEntity entity = (CustomerInfoEntity)object;
			if(SmartFoxClient.helperId.equals(entity.getId())){
				Intent intent = new Intent();
				intent.setClass(this,ChatActivity.class);
				intent.putExtra(ChatActivity.KEY_PARAME, entity);
				startActivity(intent);
			}else{
				FriendHttpUtil.onItemClick(this, entity);
			}
		}else if(object instanceof GroupInfoEntity ){
			SalonHttpUtil.onItemClick(this, this, getSupportFragmentManager(),(GroupInfoEntity)object,true);
		}
		return true;
	}
	
	
	//门票
	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if(isFinishing())return;
		if("1".equals(state)){
			Intent  intent1 = new Intent(this,ChatActivity.class);
			intent1.putExtra(ChatActivity.KEY_PARAME,entity);
			startActivity(intent1);
		}else if("0".equals(state)){
//			ToastUtil.showLong(this,"多美币不足");
		}else if("-1".equals(state)){
			ToastUtil.showLong(this,"支付失败");
		}
	}

	
	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(this,mSalonName);
	}

	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this, null, entity);
	}
	
	
	public void deleteMessageFromUserID(final String userID){
		final ConcurrentHashMap<String,List<MessageEntity>> map = HTalkApplication.getAppData().messageCllection;
		//有消息需要删除消息
		if(map.containsKey(userID)){
			List<MessageEntity> list = map.get(userID);
			final JSONArray buffer=new JSONArray();
			for (MessageEntity messageEntity : list) {
				String id = messageEntity.getServerId();
				if(id == null)continue;
				buffer.put(id);
			}
			HttpRestClient.doHttpDeleteLeaveOnlineMessage(SmartFoxClient.getLoginUserId(),buffer.toString(),new AsyncHttpResponseHandler(this){
				@Override
				public void onSuccess(String content) {
					super.onSuccess(content);
					JSONObject jsonObject;
					try {
						jsonObject = new JSONObject(content);
						if(1==jsonObject.optInt("error_code",-1)){//删除成功
							final List<MessageEntity> list = HTalkApplication.getAppData().messageCllection.get(userID);
							if(list != null)HTalkApplication.getAppData().messageCllection.remove(userID);
							List<String> strings=new ArrayList<String>();
							for (int i = 0; i < buffer.length(); i++) {
								HTalkApplication.getAppData().messageMap.remove(buffer.get(i).toString());
								strings.add(buffer.get(i).toString());
							}
							ChatUserHelper.getInstance().updateChatMesageDeleteState(strings);
						}else{
							ToastUtil.showToastPanl(jsonObject.optString("error_message","删除失败"));
						}
						mHandler.sendEmptyMessage(1);
					} catch (JSONException e) {
					}
				}
			});
		}
}
}
